package com.example.controller;


import com.example.domain.Main;
import com.example.repository.MainRepository;
import com.example.service.MainService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.List;

/**
 * Created by 李强 on 2017/4/28.
 *  数据库
 *  增删改查
 */
@RestController
public class MainController {
    //日志
     private final static Logger logger= LoggerFactory.getLogger(MainController.class);

    @Autowired
     private MainRepository mainRepository;

     @Autowired
     private MainService mainService;

    @GetMapping(value = "/mains")
     public List<Main> mainList(){

          logger.info("mainList");

          return mainRepository.findAll();

    }
    //添加一个女生 18岁少女禁止入内
     @PostMapping(value = "/mans")
    public Main mainAdd(@Valid  Main main ,BindingResult bindingResult){
      if (bindingResult.hasErrors()){
          System.out.println(bindingResult.getFieldError().getDefaultMessage());
          return null;
      }
        main.setAge(main.getAge());
        main.setCupSize(main.getCupSize());
        return mainRepository.save(main);
     }

     //查询一个女生
    @GetMapping(value = "/main/{id}")
    public Main mainFindOne(@PathVariable("id") Integer id){
        return mainRepository.findOne(id);
    }

    //更新一个女生
    @PutMapping(value = "/mns/{id}")
    public Main mainUpdate(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age){
        Main main=new Main();
        main.setId(id);
        main.setCupSize(cupSize);
        main.setAge(age);
        return mainRepository.save(main);
    }

    //删除一个女生
    @DeleteMapping(value = "mis/{id}")
    public void mainDelete(@PathVariable("id") Integer id){
        mainRepository.delete(id);

    }

    //通过年龄查询
    @GetMapping(value = "main/age")
    public List<Main> mainListByAge(@PathVariable("age") Integer age){
       return mainRepository.findByAge(age);

    }
    @PostMapping(value = "main/tow")
    public void mainT(){
        mainService.insertTow();
    }

}
